<template>
  <div>
    <el-form :model="form" :rules="rules" ref="bookForm" label-width="80px">
      <el-form-item label="书名" prop="title">
        <el-input v-model="form.title"></el-input>
      </el-form-item>
      
      <el-form-item label="作者" prop="author">
        <el-input v-model="form.author"></el-input>
      </el-form-item>
      
      <el-form-item label="库存" prop="copies">
        <el-input-number v-model="form.copies" :min="1"></el-input-number>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="$emit('cancel')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        title: '',
        author: '',
        copies: 1
      },
      rules: {
        title: [
          { required: true, message: '请输入书名', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '请输入作者', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm() {
      this.$refs.bookForm.validate((valid) => {
        if (valid) {
          this.$emit('submit', this.form)
          this.resetForm()
        } else {
          return false
        }
      })
    },
    resetForm() {
      this.$refs.bookForm.resetFields()
    }
  }
}
</script>